package org.lixf.socket.tomcat.v1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class BlockServer {

    private static final int port = 8090;

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port); // 监听指定端口
        System.out.println("server is running on " + port);
        while (serverSocket.isBound() && !serverSocket.isClosed()) {
            Socket socket = serverSocket.accept();
            System.out.println("==================================");
            System.out.println("Process new http request... connected from " + socket.getRemoteSocketAddress());
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                // 读取HTTP请求:
                String firstLine = reader.readLine();
                if (firstLine == null) {
                    // postman 会请求两次 第一次为空
                    // ServerImpl:
//                    if (requestLine == null) {
//                        /* connection closed */
//                        closeConnection(connection);
//                        return;
//                    }
                    System.out.println("第一次 " + socket.getRemoteSocketAddress());
                    continue;
                }
                System.out.println("first line " + firstLine);
                System.out.println("****************header******************");
                for (; ; ) {
                    String header = reader.readLine();
                    if (header.isEmpty()) { // 读取到空行时, HTTP Header读取完毕
                        break;
                    }
                    System.out.println(header);
                }
                // 发送成功响应:
                String body = "<html><body><h1>Hello, world!</h1></body></html>";
                String response = "HTTP/1.0 200 OK\r\n" +
                        "Connection: close\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: " + body.length() + "\r\n" +
                        "\r\n" + // 空行标识Header和Body的分隔
                        body; // body
                writer.write(response);
                writer.flush();
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    socket.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
                System.out.println("client disconnected.");
            } finally {
                System.out.println("socket is closed? " + socket.isClosed());
            }
        }
    }
}

